using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Windows.Input;
using Microsoft.Practices.Prism.Commands;

namespace TrackMe.Apps.VM
{
    [Export]
    public class TaskSearchVM : BasicViewModel<ISearchView>
    {
        private IList<ITaskForSelectVM> found = new List<ITaskForSelectVM>();
		#pragma warning disable 0649
        [Import]
        private IDatabase database;
        [Import("SelectTask")]
        private ICommand selectTaskCmd;
		[Import]
		private TfsSyncControl tfsSync;
		#pragma warning restore 0649

		public ICommand RefreshTfsCmd { get; private set; }

        [ImportingConstructor]
        public TaskSearchVM(ISearchView view) : base(view)
        {
            WaitMessage = "Please wait";
			RefreshTfsCmd = new DelegateCommand(RefreshTfs);
        }

    	private void RefreshTfs()
    	{
    		ViewCore.IsRefreshingTFS = true;
			tfsSync.DoOnComplete(() =>
			{
				ViewCore.IsRefreshingTFS = false;
			    FetchTasks();
			});
			tfsSync.Heartbeat(true);
		}

    	private string searchFor;
        public string SearchFor
        {
            get { return searchFor; }
            set
            {
                if (searchFor != value)
                {
                    searchFor = value;
                    FetchTasks();
                }
            }
        }

        public int Selected { get; set; }

        private void FetchTasks()
        {
            var tasks = database.SearchForTask(SearchFor);
            var vms = new List<ITaskForSelectVM>();
            foreach (var task in tasks)
            {
                var vm = AutoIntf.New<ITaskForSelectVM>();
                vm.Model = task;
                vm.SelectCmd = selectTaskCmd;
                vms.Add(vm);
            }
            Found = vms;
        }

        public IList<ITaskForSelectVM> Found
        {
            get { return found; }
            set
            {
                if (value != found)
                {
                    found = value;
                    RaisePropertyChanged(() => Found);
                }
            }
        }

        public string WaitMessage { get; private set; }
    }
}
